var datePicker;
var multiplePicker;
var $cityPicker;

var item = {
  id: -1,
  image: "assets/img/avatars/3.jpg",
  text: "Vue-Bootstrap",
  description: "<strong>Description information</strong>",
  number: 987.654321,
  contacts: '{"qq":"123456","mobile":"13612345678"}',
  address: {province: "广东省", city: "广州市", county: "黄埔区", street: "创新大道1号"},
  deleted: false,
  createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
  updateTime: moment().format('YYYY-MM-DD HH:mm:ss')
};
var itemsManagerOptions = {
  api: {
    base: "/api/items",
    list: "",
    insert: "",
    update: "",
    delete: "",
    query: "/query",
    batchDeletes: "/batch/deletes"
  },
  paging: {
    clientSize: 10,
    serverSize: 100,
    pageSizeOptions: [
      {
        text: "5",
        value: 5
      }, {
        text: "10",
        value: 10
      }, {
        text: "20",
        value: 20
      },
      {
        text: "50",
        value: 50
      }, {
        text: "100",
        value: 100
      }]
  }
};
var itemsManager = null;

function query() {
  var addresses = $cityPicker.val().split("/");
  var keyword = $("#keyword").val();
  var timeRange = datePicker.val().split("~");
  var contacts = multiplePicker.val();
  var startTime = timeRange[0];
  var endTime = timeRange[1];

  var query = {keyword: keyword,address:{province:addresses[0],city:addresses[1],county:addresses[2]},startTime: startTime+":00",endTime:endTime+":00", contacts: contacts};

  axios.post(itemsManagerOptions.api.query, query)
      .then(function (response) {
        itemsManager.replaceItems(response.data.items)
        itemsManager.paging.serverTotal = response.data.totalCount;
      })
      .catch(function (error) {
        toastr.error(error, '错误');
        console.log(error);
      });
}

function toastrSetup(){
  toastr.options = {
    closeButton: true,
    debug: false,
    newestOnTop: false,
    progressBar: true,
    positionClass: "toast-top-right",
    preventDuplicates: false,
    onclick: null,
    showDuration: "300",
    hideDuration: "1000",
    timeOut: "5000",
    extendedTimeOut: "1000",
    showEasing: "swing",
    hideEasing: "linear",
    showMethod: "fadeIn",
    hideMethod: "fadeOut"
  };
}

function axiosSetup(){
  // 配置axios请求的地址
  axios.defaults.baseURL = itemsManagerOptions.api.base;
  axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
  axios.defaults.timeout = 5000;
  axios.interceptors.response.use(
      function (response) {
        //对响应数据做些事
        return response;
      },
      function (error) {
        //请求错误时做些事
        toastr.error("服务器出错了，请稍后再试！", "错误");
        return Promise.reject(error);
      }
  );
}

$(function () {

  toastrSetup();

  axiosSetup();

  Vue.filter('jsonParse', function (value) {
    if (!value) return {};
    return JSON.parse(value);
  });
  Vue.filter('digitalFormat', function (value, digit) {
    if (!value) return '';
    value = value.toFixed(digit);
    return value;
  });

  itemsManager = new Vue({
    el: "#items-manage",
    data: {
      queryItem: {
        text: "text",
        period: "2020-02-20-2020-02-20"
      },
      items: [],
      paging: {
        size: itemsManagerOptions.paging.clientSize,
        offset: 0,
        serverSize: itemsManagerOptions.paging.serverSize,
        serverTotal: 0
      },
      formItem: item,
      detailItem: item,
      deleteItems: {},
      options: itemsManagerOptions
    },
    computed: {
      pageItems: function pageItems() {
        var startIndex = this.paging.size * this.paging.offset;
        var endIndex = startIndex + this.paging.size - 1;
        return this.items.filter(function (value, index) {
          return index >= startIndex && index <= endIndex;
        });
      },
      pageLinks: function pageLinks() {
        var links = [1];
        var i;
        var pageCount = Math.ceil(this.paging.serverTotal / this.paging.size);

        if (pageCount <= 8) {
          for (i = 2; i <= pageCount; i++) {
            links.push(i);
          }
        } else {
          var start = this.paging.offset - 2;
          var end = this.paging.offset + 3 >= pageCount ? pageCount - 1 : this.paging.offset + 2;

          if (start > 2) {
            for (i = start; i <= end; i++) {
              links.push(i);
            }
          } else {
            for (i = 2; i <= 6; i++) {
              links.push(i);
            }
          }

          if (this.paging.offset > 4) {
            links.splice(1, 0, "...");
          }

          if (this.paging.offset + 3 < pageCount) {
            links.splice(8, 0, "...");
          }

          links.push(pageCount);
        }

        return links;
      }
    },
    methods: {

      adaptItems: function (items) {
        return _.map(items, function (item, index) {
          item.checked = false;
          return item;
        });
      },
      replaceItems: function (items) {
        var adaptedItems = this.adaptItems(items);
        itemsManager.items.splice(0, this.items.length);
        itemsManager.items = this.items.concat(adaptedItems);
      },
      appendItems: function (items) {
        var adaptedItems = this.adaptItems(items);
        this.items = this.items.concat(adaptedItems);
      },
      dateTimeFormat: function dateTimeFormat(dateTime) {
        return moment(dateTime).format("YYYY-MM-DD HH:mm:ss");
      },
      parseJSON:function(jsonString){
        if(!jsonString) return {};
        return JSON.parse(jsonString);
      },
      createItem: function createItem() {
        return JSON.parse(JSON.stringify(item));
      },
      validateForm: function validateForm() {
        var form = $("#item-form").get(0);
        var validated = form.checkValidity();
        form.classList.add("was-validated");
        return validated;
      },
      checkAll: function($event){
        var checked  = $event.target.checked;
        _.forEach(this.pageItems, function (item, index) {
          if (item) {
            item.checked = checked;
          }
        });
      },
      confirmRemove: function confirmRemove(item) {
        this.deleteItems = item;
        $("#confirm-modal").modal("show");
      },
      confirmRemoveAll: function confirmRemoveAll() {
        var deletes = _.filter(this.items, function (item) {
          return item.checked;
        });

        if (deletes.length > 0) {
          this.deleteItems = deletes;
          $("#confirm-modal").modal("show");
        } else {
          toastr.warning("未选取需要删除的元素！");
        }
      },
      showDetails: function showDetails(item) {
        this.detailItem = item;
        $("#detail-modal").modal("show");
      },
      showItemForm: function showItemForm(item) {
        if (!item || item === undefined) {
          item = this.createItem();
        }
        this.formItem = JSON.parse(JSON.stringify(item));
        $("#item-form").removeClass("was-validated");
        $("#form-modal").modal("show");
      },
      removeItems: function removeItems() {
        if (this.deleteItems instanceof Array) {
          //批量删除
          var ids = [];
          _.reverse(this.deleteItems);
          _.forEach(this.deleteItems, function (item) {
            ids.push(item.id);
          });


          axios.post(this.options.api.batchDeletes, ids)
              .then(function (response) {
                if (response.status == 200) {
                  var itemIndex = -1;
                  _.forEach(itemsManager.deleteItems, function (item) {
                    itemIndex = _.findIndex(itemsManager.items, function(o) { return o.id == item.id; });
                    itemsManager.items.splice(itemIndex, 1);
                  });
                  itemsManager.deleteItems = null;
                  toastr.success("删除成功！");
                } else {
                  toastr.error("删除出错！");
                }
              })
              .catch(function (error) {
                toastr.error(error, '错误');
                console.log(error);
              });

        } else {
          //单条记录删除
          axios.delete(this.options.api.delete + this.deleteItems.id)
              .then(function (response) {
                if (response.status == 204) {
                 var  itemIndex = _.findIndex(itemsManager.items, function(o) { return o.id == itemsManager.deleteItems.id; });
                  itemsManager.items.splice(itemIndex, 1);
                  toastr.success("删除成功！");
                } else {
                  toastr.error("删除出错！");
                }
              })
              .catch(function (error) {
                toastr.error(error, '错误');
                console.log(error);
              });
        }
      },
      saveItem: function saveItem() {
        var validated = this.validateForm();
        if (validated) {
          if (this.formItem.id === -1) {
            //新增
            axios.post(this.options.api.insert, this.formItem)
                .then(function (response) {
                  if(response.status = 201){
                    var index = itemsManager.paging.offset * itemsManager.paging.size;
                    itemsManager.formItem.id = response.data.id;
                    // itemsManager.formItem.contacts = JSON.parse(itemsManager.formItem.contacts);
                    itemsManager.items.splice(index, 0, itemsManager.formItem);
                    toastr.success("保存成功！");
                    console.log(response);
                  }else{
                    toastr.error(error, response.status);
                  }

                })
                .catch(function (error) {
                  toastr.error(error, '错误');
                  console.log(error);
                });
          } else {
            //更新
            axios.put(this.options.api.update, this.formItem)
                .then(function (response) {
                  if(response.status = 201) {
                    Vue.set(itemsManager.items, itemsManager.formItem.index, itemsManager.formItem);
                    toastr.success("保存成功！");
                    console.log(response);
                  }else{
                    toastr.error(error, response.status);
                  }
                })
                .catch(function (error) {
                  toastr.error(error, '错误');
                  console.log(error);
                });

          }
          $("#form-modal").modal("hide");
        }
      }
    },
    watch: {
      "paging.size": function pagingSize(newVal, oldVal) {
        this.paging.offset = Math.floor(this.paging.offset * oldVal / newVal);
        return;
      },
      "paging.offset": function pagingOffset(newVal, oldVal) {
        var startIndex = this.paging.size * newVal;
        var endIndex = startIndex + this.paging.size - 1;
        if (
            startIndex >= this.items.length ||
            this.items[startIndex] == null ||
            (endIndex <= this.paging.serverTotal && this.items[endIndex] == null)
        ) {
          var serverPageStartIndex = Math.floor(
              startIndex / this.paging.serverSize
          );
          var serverPageEndIndex = Math.floor(
              endIndex / this.paging.serverSize
          );
          var insertStartIndex = serverPageStartIndex * this.paging.serverSize;
          var insertEndIndex =
              (serverPageEndIndex + 1) * this.paging.serverSize - 1;
          var offset = serverPageStartIndex;
          var size =
              (serverPageEndIndex - serverPageStartIndex + 1) *
              this.paging.serverSize;

          var url =
              this.options.api.list +
              "?offset=" +
              offset +
              "&size=" +
              size;
          axios.get(url)
              .then(function (response) {
                var items = itemsManager.adaptItems(response.data.items);
                if (insertStartIndex === itemsManager.items.length) {
                  itemsManager.items = itemsManager.items.concat(items);
                } else {
                  var i;
                  if (insertStartIndex > itemsManager.items.length) {
                    for (i = itemsManager.items.length; i < insertStartIndex; i++) {
                      itemsManager.items.push(null);
                    }
                    itemsManager.items = itemsManager.items.concat(items);
                  } else {
                    for (i = insertStartIndex; i <= insertEndIndex; i++) {
                      itemsManager.items.splice(i, 1, items[i - insertStartIndex]);
                    }
                  }
                }
              }).catch(function (error) {
            toastr.warning("服务器出错了，请稍后再试！");
            console.log(error);
            return;
          });
        }
      }
    },
    created: function () {
      axios.get(this.options.api.list)
          .then(function (response) {
            itemsManager.replaceItems(response.data.items)
            itemsManager.paging.serverTotal = response.data.totalCount;
          })
          .catch(function (error) {
            toastr.error(error, '错误');
            console.log(error);
          });
    }

  });

  multiplePicker = $(".multiple-select-picker").select2({
    theme: "coreui",
    placeholder: "联系方式",
    // maximumSelectionLength: 3,
    // allowClear   : true,
    closeOnSelect: false,
    tags: true
  });

  datePicker = $(".date-range-picker").daterangepicker({
    // singleDatePicker: true,
    timePicker: true,
    timePicker24Hour: true,
    opens: "left",
    locale: {
      separator: "~",
      applyLabel: "应用",
      cancelLabel: "取消",
      fromLabe: "从",
      toLabel: "到",
      weekLabel: "W",
      customRangeLabel: "自定义",
      // format          : 'YYYY-MM-DD HH:mm:SS',
      format: 'YYYY-MM-DD HH:mm',
      daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
      monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
    },
    ranges: {
      今天: [moment(), moment()],
      昨天: [moment().subtract(1, "days"), moment().subtract(1, "days")],
      最近7天: [moment().subtract(6, "days"), moment()],
      最近30天: [moment().subtract(29, "days"), moment()],
      这个月: [moment().startOf("month"), moment().endOf("month")],
      上个月: [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")]
    },
    buttonClasses: "btn btn-sm mx-1",
    applyButtonClasses: "btn-primary",
    cancelClass: "btn-secondary"
  });

  $cityPicker = $("#city-picker");

  $('#city-reset').click(function () {
    $cityPicker.citypicker('reset');
  });

  $('#city-destroy').click(function () {
    $cityPicker.citypicker('destroy');
  });
});